package com.sxu.demo;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@RequestMapping("/session")
@RestController
public class SessionController {
    //获取Cookie

    //servlet方式
    @RequestMapping("/getC")
    public String gstCookie(HttpServletRequest request, HttpServletResponse response) {

        Cookie[] cookies = request.getCookies();
        if(cookies != null) {
            Arrays.stream(cookies).forEach(cookie -> {
                System.out.println(cookie.getName() + ":" + cookie.getValue());
            });
        }
        return "获取Cookie";
    }

    @RequestMapping("/getC2")
    public String gstCookie2(@CookieValue("bite")String bite) {
        return "从Cookie中获取值，bite："+bite;
    }


    //设置Session —— session不能伪造，只能自己设置
    @RequestMapping("/setS")
    public String setSession(HttpServletRequest request, HttpServletResponse response) {
        //从Cookie中获取sessionId 再根据sessionId获取session
        //如果没有获取到 就会创建一个session
        HttpSession session = request.getSession();
        session.setAttribute("name","zhangsan");
        return "设置session成功";
    }

    //获取Session
    //servlet方式
    @RequestMapping("/getS")
    public String gstSession(HttpServletRequest request, HttpServletResponse response) {
        //从Cookie中获取sessionId 再根据sessionId获取session
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("name");
        return "从session中获取name"+name;
    }

    //直接使用HttpSession
    @RequestMapping("/getS2")
    public String gstSession2(HttpSession session) {
        String name = (String) session.getAttribute("name");
        return "从session中获取name"+name;
    }

    //使用注解:
    @RequestMapping("/getS3")
    public String gstSession3(@SessionAttribute("name") String name) {
        return "从session中获取name"+name;
    }

    //获取Header
    //传统方式获取
    @RequestMapping("getH")
    public String gstHeader(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return "从Header中获取信息,userAgent"+userAgent;
    }

    //使用注解
    @RequestMapping("getH2")
    public String gstHeader2(@RequestHeader("User-Agent") String userAgent) {
        return "从Header中获取信息,userAgent"+userAgent;
    }
}



